package me.flyray.bsin.server.utils;

import com.alibaba.fastjson.JSON;
import me.flyray.bsin.server.common.ResponseCode;
import me.flyray.bsin.server.exception.BusinessException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import cn.hutool.core.bean.BeanUtil;

import java.util.HashMap;
import java.util.Map;

public class HttpPostRequest {

    public static void httpPostWithJsonAndHeader(String url,Map<String,Object> bizParams, Map<String, String> headsMap) {
        Map<String,Object> map = new HashMap<>();
        map.put("serviceName","WebSocketService");
        map.put("methodName","sendTo");
        map.put("bizParams",bizParams);

        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(JSON.toJSONString(map), "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        //头
        if (headsMap != null && !headsMap.isEmpty()) {
            headsMap.forEach(httpPost::addHeader);
        }
        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(httpPost)) {

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                System.out.println("http请求成功");

            } else {
                System.out.println("http请求失败");
                throw new BusinessException(ResponseCode.PUSH_MESSAGE_FAIL);
            }
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.PUSH_MESSAGE_FAIL);
        }
    }
}
